<template>
	<view class="share-page" :style="{ height: canvasHeight + 200 + 'px' }">
		<view class="share-page-box" id="box" v-if="show"
			:style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }">
			<wxml-to-canvas class="widget" :width="canvasWidth" :height="canvasHeight" />
		</view>
		<view class="share-page-box msg-box" v-else :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }">
			{{ msg }}
		</view>
		<view v-if="reportImg" class="noneText">
			<text>图片已经上传到服务器</text>
		</view>
		<view class="share-page-btn" @tap="extraImage">
			<button class="btn-big" style="
          margin: 15px 0;
          background: #1a66ff;
          color: #fff;
          width: 100%;
          padding: 5px;
        " size="mini">
				保存图片
			</button>
		</view>
	</view>
</template>
<script>
	import baseUrl from "@/request/baseUrl.js";
	const {
		wxml,
		style
	} = require("./DomData.js");
	export default {
		name: "",
		data() {
			return {
				show: false, // 是否显示canvas
				// canvasWidth: 650, // 595, // 默认canvas宽高
				// canvasHeight: 920,
				// screenWidth: 920, // 设备宽度
				canvasWidth: 800, // 595, // 默认canvas宽高
				canvasHeight: 1300,
				screenWidth: 1140, // 设备宽度
				name: "",
				pic: "",
				chapter1: "",
				chapter2: "",
				widget: null,
				msg: "加载中，请稍等...", // 提示语
				form: {
					id: "",
					report: "",
				},
				reportImg: "", // 已生成报告图片
			};
		},
		onLoad(options) {
			console.log("options", options);
			this.form.id = options.id;
			this.reportImg = options.reportImg || "";

			this.canvasHeight = this.screenWidth;
			console.log("screenWidth----------", this.screenWidth);
			this.show = true;
			// 数字容器宽度 动态设置
			setTimeout(() => {
				wx.showLoading({
					title: "图片生成中...",
				});
				this.widget = this.selectComponent(".widget");
				this.renderToCanvas();
			}, 1000);
			// 获取设备信息
			// wx.getSystemInfo({
			//   success: (res) =>{
			//     this.screenWidth = res.screenWidth
			//     this.canvasWidth = this.screenWidth * 0.9
			//     this.canvasHeight = this.screenWidth*2.7
			//     console.log('screenWidth', this.screenWidth)
			//     this.show = true
			//     // 数字容器宽度 动态设置
			//     setTimeout(() => {
			//       wx.showLoading({title: '图片生成中...'})
			//       this.widget = this.selectComponent('.widget')
			//       this.renderToCanvas()
			//     }, 1000)
			//   }
			// });
		},
		methods: {
			getLei(name){
				//保养
				let arr = ['CT', 'DR', 'DSA', '超声', 'MRI', 'DR/F', '小C']
				let res = arr.includes(name)
				return res ? res:""
			},
			// wxml 转 canvas
			renderToCanvas() {
				console.log("reportDetail", this.$store.state.reportDetail);
				let setData = this.$store.state.reportDetail;
				let arr = [];
				setData.repair?.map((item, index) => {
					let el = index + 1 + "." + item.repair;
					arr.push(el);
				});
				setData.logo = `https://ylsb.cqjjyl.com/uploads/my/logo.png`;
				setData.logo2 = `https://ylsb.cqjjyl.com/uploads/my/fail.png`;
				arr = arr.join(";");
				setData.repair = arr;
				setData.titleName = this.getLei(setData.leibie.name)
				console.log(setData,'===setData');
				const _wxml = wxml(setData);
				console.log(_wxml);
				const _style = style(this.screenWidth, this.canvasWidth, this.canvasHeight);
				console.log(_style);
				const p1 = this.widget.renderToCanvas({
					wxml: _wxml,
					style: _style,
				});
				p1.then((res) => {
					console.log("海报生成成功");
					wx.hideLoading();
					// this.container = res
				}).catch((err) => {
					wx.showToast({
						title: "生成失败",
						icon: "none",
					});
					wx.hideLoading();
				});
			},
			// 保存到朋友圈
			extraImage() {
				if (!this.show) {
					wx.showToast({
						title: "海报生成失败，无法分享到朋友圈",
						icon: "none",
					});
					return;
				}
				if (this.reportImg) {
					this.saveimgtoAlbum(this.reportImg);
				} else {
					const p2 = this.widget.canvasToTempFilePath();
					let that = this;
					p2.then((result) => {
						let path = result.tempFilePath;
						const token = uni.getStorageSync("userInfo").token;
						uni.uploadFile({
							url: `${baseUrl}api/common/upload`,
							filePath: path,
							name: "file",
							formData: {
								token: token,
							},
							success: async (res1) => {
								let imgUrl = JSON.parse(res1.data).data.fullurl;
								// 保存图片到相册
								await that.saveimgtoAlbum(imgUrl);
								that.form.report = imgUrl;
								this.$https.post("/warranty/edit_report", that.form).then((res) => {
									uni.showToast({
										title: res.msg,
										icon: "none",
										success: () => {
											setTimeout(() => {
												uni.navigateBack({
													delta: 1,
												});
											}, 1500);
										},
									});
								});
							},
							fail: () => {
								uni.showToast({
									title: "上传失败",
									icon: "error",
								});
							},
						});
					});
				}
			},
			// 检测是否有保存到相册权限
			saveimgtoAlbum(imgurl) {
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success: async (res) => {
							if (!res.authSetting["scope.writePhotosAlbum"]) {
								uni.showModal({
									title: "授权提示",
									content: "需要写入相册权限，请确认授权，否则图片无法保存到本地",
									showCancel: true,
									success: async ({
										confirm,
										cancel
									}) => {
										if (confirm) {
											await this.savePhoto(imgurl);
											resolve();
										} else {
											uni.showToast({
												title: "已取消授权",
												icon: "none",
												success: () => {
													setTimeout(() => {
														resolve();
													}, 1500);
												},
											});
										}
									},
									fail: (err) => {
										resolve();
									},
								});
							} else {
								await this.savePhoto(imgurl);
								resolve();
							}
						},
					});
				});
			},
			// 保存到相册
			savePhoto(imgurl) {
				console.log(imgurl,'---------')
				return new Promise((resolve, reject) => {
					uni.authorize({
						scope: "scope.writePhotosAlbum",
						success: () => {
							uni.getImageInfo({
								src: imgurl,
								success: (image) => {
									uni.saveImageToPhotosAlbum({
										filePath: image.path,
										success: () => {
											uni.showModal({
												content: "图片已保存，请在相册查看！",
												showCancel: false,
												confirmText: "确定",
												confirmColor: "#333",
												success: () => {
													resolve();
												},
											});
										},
										fail: (err) => {
											resolve();
										},
									});
								},
							});
						},
						fail: (err) => {
							uni.showToast({
								title: err.errMsg,
								icon: "none",
								success: () => {
									setTimeout(() => {
										resolve();
									}, 1500);
								},
							});
						},
					});
				});
			},
		},
	};
</script>
<style>
	/* @page{
		background-color: #E2E2E2;
	} */
	page {
		overflow: scroll;
	}
</style>
<style lang="scss" scoped>
	.share-page {
		background: #fff;
		position: relative;
		// overflow: hidden;
		min-height: 100vh;
		width: 650px;
		height: 1200px;

		.msg-box {
			display: flex;
			align-items: center;
			text-align: center;
			justify-content: center;
			flex-direction: column;
		}

		.share-page-box {
			margin: 40rpx auto;
			position: relative;
			overflow: hidden;
			box-shadow: 0rpx 6rpx 20rpx 6rpx rgba(0, 0, 0, 0.2);
		}

		.noneText {
			display: flex;
			justify-content: center;
			align-items: center;
			color: #969699;
			margin: 15px 0;
		}

		.share-page-btn {
			padding: 0 20px;

			img {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>